package pierwszy;

import java.util.List;

import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;

public class NotesListPage extends Note{
	private WebDriver driver;
	private WebDriverWait wait;
	private final String notesListPageHeader = "Notki (lista)";
	
	NotesListPage(WebDriver driver, WebDriverWait wait){
		super(driver, wait);
		this.driver = driver;
		this.wait = wait;
		
		if(!getNotesListPageHeader().getText().equals(notesListPageHeader)){
			throw new NoSuchWindowException("This is not the NotesList page");
		}
		
//		if(!getIconPlusText().getText().equals(KsPDKPage.iconPlusOptionsMap.get("Notkę"))){
//			throw new NoSuchWindowException("This is not the Note page");
//		}
	}
		
	public NoteContentPage openLastNote(){
		WebElement lastNote;
		List<WebElement> notesIdList = driver.findElements(NotesListPageUiMapping.notesIdList);
		
		//System.out.println("Max note ID: " + getMaxId(notesIdList));
		
		lastNote = getLastNote(notesIdList);
		
		lastNote.click();
		
		return new NoteContentPage(driver, wait);
	}
	
	public NotesListPage deleteLastNoteAccept(){
		WebElement lastNote;
		List<WebElement> notesOptionList = driver.findElements(NotesListPageUiMapping.notesOptionList);
		
		//System.out.println("Max note ID: " + getMaxId(notesIdList));
		
		lastNote = getLastNote(notesOptionList);
		
		lastNote.click();
		
		driver.switchTo().alert().accept();
		
		return this;
	}
	
	public NotesListPage deleteLastNoteDismiss(){
		WebElement lastNote;
		List<WebElement> notesOptionList = driver.findElements(NotesListPageUiMapping.notesOptionList);
		
		//System.out.println("Max note ID: " + getMaxId(notesIdList));
		
		lastNote = getLastNote(notesOptionList);
		
		lastNote.click();
		
		driver.switchTo().alert().dismiss();
		
		return this;
	}
	
	//getters
	public WebElement getNotesListPageHeader(){
		return driver.findElement(NotesListPageUiMapping.notesListPageHeader);
	}
	
	//Utils
	public WebElement getLastNote(List<WebElement> notesList){
		WebElement lastNote = null;
		int maxId = 0 ;
		
		for (WebElement note : notesList){
			//maxId = Math.max(maxId, Integer.parseInt(locationId.getAttribute("href").substring(locationId.getAttribute("href").lastIndexOf("id=") + 3)));
			if(maxId < Integer.parseInt(note.getAttribute("href").substring(note.getAttribute("href").lastIndexOf("id=") + 3))){
				maxId = Integer.parseInt(note.getAttribute("href").substring(note.getAttribute("href").lastIndexOf("id=") + 3));
				lastNote = note;
			}
		}
		
		return lastNote;
	}
}
